import urllib.request
import urllib.parse
import http.cookiejar
import time
import re
from bs4 import BeautifulSoup
import json

URL_BAIDU_INDEX = u'http://www.baidu.com/'

#https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true 也可以用这个
URL_BAIDU_TOKEN = 'https://passport.baidu.com/v2/api/?getapi&tpl=pp&apiver=v3&class=login'
URL_BAIDU_LOGIN = 'https://passport.baidu.com/v2/api/?login'
URL_BAIDU_VERYIMAGE='https://passport.baidu.com/cgi-bin/genimage?'
# 设置用户名、密码
username = '微笑的小小刀'
password = 'BeMyself'

cookie = http.cookiejar.CookieJar()
chandle = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(chandle)
urllib.request.install_opener(opener)


def getData(url):
    r = urllib.request.Request(url)
    u = opener.open(r)
    data = u.read()
    try:
        data = data.decode('utf-8')
    except:
        data = data.decode('gbk', 'ignore')
    return data

def getImage(url,fileName):
    r = urllib.request.Request(url)
    u = opener.open(r)
    data = u.read()
    binfile = open(str(fileName), "wb")
    binfile.write(data)
    binfile.close()


def postData(url, data):
    data = urllib.parse.urlencode(data)
    data = bytes(data, 'utf-8')
    r = urllib.request.Request(url, data)
    for eachcookie in cookie:
        print(eachcookie.name)
    r.add_header('Content-Type', 'application/x-www-form-urlencoded')

    u = urllib.request.urlopen(r)
    data = u.read()
    print(data.decode('gbk','ignore'))
    try:
        data = data.decode('utf-8')
    except:
        data = data.decode('gbk', 'ignore')
    return data


def timeNow():
    return int(round(time.time()*1000))

# 先访问 www.baidu.com 获取BAIDUID
baiduIDRequest = getData(URL_BAIDU_INDEX)

# 请求 passport.baidu.com/v2/api/?getapi 获取token

# 请求需要带的变量
par = {
        "apiver": 'v3',
        "callback": 'bd__cbs__sg2a9',
        "class": 'login',
        "logintype": 'dialogLogin',
        "tpl": 'tb',
        "tt": timeNow()
    }
# 变量编码并请求
url = 'https://passport.baidu.com/v2/api/?getapi&%s' % urllib.parse.urlencode(par)
token = re.findall('"token" : "(.*?)"', getData(url))[0]
# 加入新的变量，做用户名校验，如果校验失败，则返回值
# 中的codeString是下一步请求验证码时需要的字段,
par.update({"isphone": 'false', "username": username, "token": token})
url = 'https://passport.baidu.com/v2/api/?logincheck&?%s' % urllib.parse.urlencode(par)
checkData = getData(url)
print(checkData)
codeString = re.findall('"codeString" : "(.*?)"', checkData)[0]
if(codeString==''):
    print("不需要验证码")
    verifyCode = ""
else:
    print("需要验证码")
    # 需要验证码的情况，向百度请求验证码
    image_url = 'https://passport.baidu.com/cgi-bin/genimage?%s' %codeString
    getImage(image_url, 'veryCode.png')
    verifyCode = input()
par.update({"codestring": str(codeString)})

# 根据token请求登录时的key字段
key_par = {
    "token": token,
    "apiver": 'v3',
    "callback": 'bd__cbs__sg2a9',
    "logintype": 'dialogLogin',
    "tpl": 'tb',
    "tt": timeNow()
    }
key_url = 'https://passport.baidu.com/v2/getpublickey?%s' %urllib.parse.urlencode(key_par)
key_data = getData(key_url)
print(key_data)
rsa_key = re.findall('"key":(.*?)}', key_data)[0]
print(rsa_key)
print("rsa :===" +rsa_key)


# 添加登录请求时别的字段
data = {
        "charset": 'UTF-8',
        "token": token,
        "isPhone": "false",
        "index": "0",
        "username": username,
        #"codestring": codeString,
        "password": password,
        "ppui_logintime": '45287',
        "quick_user": '0',
        "mem_pass":"on",
        #"verifycode": verifyCode,
        'callback': 'parent.bd__cbs__sg2a9',
        'staticpage': 'http://www.baidu.com/cache/user/html/jump.html'

}

par.update(data)
print("最后登录时的par:")
print(data)
loginUrl = 'https://passport.baidu.com/v2/api/?login'
loginData = postData(loginUrl, data)
print(loginData)
print(json.loads(getData('http://tieba.baidu.com/f/user/json_userinfo')))

